﻿using System;
using EmbeddedSharp.Core;
using Zove.Runtime.Core;
using Zove.Runtime.Core.Expression;

namespace Zove.Scripting.Core
{
    public class FactorUnaryFunctionTranslator
        : CSharpCodeTranslator
    {
        protected readonly string Subject = string.Empty;

        public FactorUnaryFunctionTranslator(
            IFunctionManager funMgr, string subject)
            : base(funMgr)
        {
            Subject = subject;
        }

        public override object Visit(IdentifierNode node)
        {
            var fn = node as FactorNode;
            if (fn == null)
            {
                throw new ArgumentException(
                    "The node should be of FactorNode", "node");
            }

            string name = fn.Factor.Name;
            if (fn.Factor == null)
            {
                throw new ArgumentException("Factor is null");
            }
            if (fn.Factor.Model != null
                     && fn.Factor.Model.Instance.Name != null)
            {
                name = fn.Factor.Model.Instance.Name + "." + fn.Factor.Name;
            }
            if (Subject == name)
            {
                return "x";
            }

            if (fn.Factor.Status != RuntimeFactorStatus.Unknown)
            {
                return fn.Factor.Value;
            }

            throw new Exception(
                string.Format(
                    "Factor {0} must be specified.", fn.Factor.Name));
        }
    }
}